import { _decorator, Component, Node, DirectionalLight, Color, Vec3 } from 'cc';
import { GameEvents } from '../constants/GameConstants';
import { EventManager } from '../core/EventManager';
import { TimeManager } from './TimeManager';

const { ccclass, property } = _decorator;

/**
 * 昼夜循环系统
 * 
 * 功能：
 * 1. 管理游戏内时间流逝
 * 2. 控制环境光照变化
 * 3. 处理昼夜相关事件
 * 4. 影响生物行为模式
 * 
 * 特点：
 * 1. 平滑的光照过渡
 * 2. 动态天气系统
 * 3. 生物行为调整
 * 4. 环境氛围营造
 */
@ccclass('DayNightSystem')
export class DayNightSystem extends Component {
    @property(DirectionalLight)
    private sunLight: DirectionalLight | null = null;

    @property
    private dayDuration: number = 1200; // 一天的持续时间（秒）

    @property
    private startHour: number = 6; // 游戏开始时间

    @property({ type: Color })
    private dayLightColor: Color = new Color(255, 255, 255);

    @property({ type: Color })
    private nightLightColor: Color = new Color(40, 40, 60);

    @property({ type: Color })
    private dawnLightColor: Color = new Color(255, 200, 150);

    @property({ type: Color })
    private duskLightColor: Color = new Color(255, 150, 100);

    private currentTime: number = 0;
    private currentHour: number = 6;
    private isNight: boolean = false;

    // 时间段定义
    private readonly DAWN_START: number = 5;  // 黎明开始
    private readonly DAY_START: number = 7;   // 白天开始
    private readonly DUSK_START: number = 17; // 黄昏开始
    private readonly NIGHT_START: number = 19; // 夜晚开始

    onLoad() {
        this.initializeTime();
        this.setupEventListeners();
    }

    private initializeTime() {
        this.currentHour = this.startHour;
        this.currentTime = (this.startHour / 24) * this.dayDuration;
        this.updateLighting(this.currentHour);
    }

    private setupEventListeners() {
        EventManager.instance.on(GameEvents.GAME_PAUSE, this.onGamePause, this);
        EventManager.instance.on(GameEvents.GAME_RESUME, this.onGameResume, this);
    }

    update(dt: number) {
        // 更新时间
        this.currentTime += dt;
        if (this.currentTime >= this.dayDuration) {
            this.currentTime = 0;
            this.onDayComplete();
        }

        // 计算当前小时
        const newHour = Math.floor((this.currentTime / this.dayDuration) * 24);
        if (newHour !== this.currentHour) {
            this.onHourChange(newHour);
        }
        this.currentHour = newHour;

        // 更新光照
        this.updateLighting(this.currentHour);
    }

    private updateLighting(hour: number) {
        if (!this.sunLight) return;

        // 计算太阳角度
        const sunRotation = new Vec3(
            -90 + (hour / 24) * 360,
            0,
            0
        );
        this.sunLight.node.eulerAngles = sunRotation;

        // 计算光照颜色
        let targetColor: Color;
        let intensity: number;

        if (hour >= this.DAWN_START && hour < this.DAY_START) {
            // 黎明
            const t = (hour - this.DAWN_START) / (this.DAY_START - this.DAWN_START);
            targetColor = Color.lerp(new Color(), this.nightLightColor, this.dawnLightColor, t);
            intensity = this.lerp(0.2, 0.8, t);
        } else if (hour >= this.DAY_START && hour < this.DUSK_START) {
            // 白天
            targetColor = this.dayLightColor;
            intensity = 1.0;
        } else if (hour >= this.DUSK_START && hour < this.NIGHT_START) {
            // 黄昏
            const t = (hour - this.DUSK_START) / (this.NIGHT_START - this.DUSK_START);
            targetColor = Color.lerp(new Color(), this.duskLightColor, this.nightLightColor, t);
            intensity = this.lerp(0.8, 0.2, t);
        } else {
            // 夜晚
            targetColor = this.nightLightColor;
            intensity = 0.2;
        }

        // 应用光照设置
        this.sunLight.color = targetColor;
        this.sunLight.illuminance = intensity * 100000;

        // 更新环境效果
        this.updateEnvironmentEffects(hour, intensity);
    }

    private updateEnvironmentEffects(hour: number, intensity: number) {
        // 更新雾效果
        const fogDensity = this.isNightTime(hour) ? 0.3 : 0.1;
        this.updateFogEffect(fogDensity);

        // 更新环境音效
        this.updateAmbientSounds(hour);

        // 更新粒子效果
        this.updateParticleEffects(hour, intensity);
    }

    private updateFogEffect(density: number) {
        // 实现雾效果更新
    }

    private updateAmbientSounds(hour: number) {
        const audioManager = this.getComponent('AudioManager');
        if (!audioManager) return;

        if (this.isNightTime(hour)) {
            audioManager.playAmbient('night');
        } else {
            audioManager.playAmbient('day');
        }
    }

    private updateParticleEffects(hour: number, intensity: number) {
        // 实现粒子效果更新
    }

    private onHourChange(newHour: number) {
        // 检查日夜转换
        const wasNight = this.isNight;
        this.isNight = this.isNightTime(newHour);

        if (wasNight !== this.isNight) {
            this.onDayNightTransition();
        }

        // 发送小时变化事件
        EventManager.instance.emit(GameEvents.HOUR_CHANGE, {
            hour: newHour,
            isNight: this.isNight
        });
    }

    private onDayNightTransition() {
        // 发送日夜转换事件
        EventManager.instance.emit(GameEvents.DAY_NIGHT_CHANGE, {
            isNight: this.isNight,
            hour: this.currentHour
        });

        // 调整生物行为
        this.adjustCreatureBehavior();
    }

    private onDayComplete() {
        EventManager.instance.emit(GameEvents.DAY_COMPLETE, {
            dayCount: TimeManager.instance.getCurrentDay()
        });
    }

    private adjustCreatureBehavior() {
        // 获取场景中的所有生物
        const creatures = this.node.parent?.getComponentsInChildren('CreatureController');
        if (!creatures) return;

        // 调整每个生物的行为
        creatures.forEach(creature => {
            if (this.isNight) {
                creature.enableNightBehavior();
            } else {
                creature.enableDayBehavior();
            }
        });
    }

    private isNightTime(hour: number): boolean {
        return hour >= this.NIGHT_START || hour < this.DAWN_START;
    }

    private lerp(start: number, end: number, t: number): number {
        return start + (end - start) * Math.min(1, Math.max(0, t));
    }

    private onGamePause() {
        // 暂停时间流逝
    }

    private onGameResume() {
        // 恢复时间流逝
    }

    onDestroy() {
        EventManager.instance.off(GameEvents.GAME_PAUSE, this.onGamePause, this);
        EventManager.instance.off(GameEvents.GAME_RESUME, this.onGameResume, this);
    }
} 